# -*- coding: utf-8 -*-

from scpy.logger import get_logger
import os
import sys
import json
from collections import Counter
import datetime
import math



reload(sys)
sys.setdefaultencoding('utf-8')

logger = get_logger(__file__)

CURRENT_PATH = os.path.dirname(__file__)
if CURRENT_PATH:
    CURRENT_PATH = CURRENT_PATH + "/"


def format_trans_age(dob):
    try:
        format = '%Y-%m-%d'
        birthDay = datetime.datetime.strptime(dob,format)
        now = datetime.datetime.now()
        age = math.floor(float((now - birthDay).days)/365)
        return age
    except Exception,e:
        logger.info('FUN[format_trans_age] failed for:' + str(e))


def format_trans_workingYearSpan(beginDate,endDate):
    try:
        format = '%Y-%m-%d'
        beginTime = datetime.datetime.strptime(beginDate,format)
        endTime = datetime.datetime.strptime(endDate,format)
        workingYearSpan = math.floor(float((endTime - beginTime).days)/365)
        return workingYearSpan
    except Exception,e:
        logger.info('FUN[format_trans_workingYearSpan] failed for:' + str(e))


def companyResume_analysis(companyResume_dic):
    try:
        resume_analysis = dict()
        preCompanyList = list()
        nextCompanyList = list()
        sexList = list()
        ageList = list()
        workingExperienceList = list()
        degreeList = list()
        majorList = list()
        schoolList = list()
        workingSpanList = list()
        locationList = list()
        resume_analysis['companyName'] = companyResume_dic.companyname
        resume_analysis['resumeCount'] = len(json.loads(companyResume_dic.jsondata))
        resume_analysis['leaveingCount'] = 0

        for resumeItem in json.loads(companyResume_dic.jsondata):
            if resumeItem.get('personalInfo') :
                if resumeItem['personalInfo'].get('sex') :
                    sexList.append(resumeItem['personalInfo'].get('sex'))
                if resumeItem['personalInfo'].get('dob') :
                    ageList.append(format_trans_age(resumeItem['personalInfo'].get('dob')))
                if resumeItem['personalInfo'].get('workingExperienceYear') :
                    workingExperienceList.append(resumeItem['personalInfo'].get('workingExperienceYear'))
                if resumeItem['personalInfo'].get('location') :
                    locationList.append(resumeItem['personalInfo'].get('location'))
            if resumeItem.get('educationInfo') :
                degreeList.append(resumeItem['educationInfo'][0].get('degree'))
                majorList.append(resumeItem['educationInfo'][0].get('major'))
                schoolList.append(resumeItem['educationInfo'][0].get('school'))

            if resumeItem.get('workingExperienceInfo') :
                for workingExperienceItem in resumeItem['workingExperienceInfo']:
                    if workingExperienceItem.get('companyName') == resume_analysis['companyName']:
                        nextIndex = resumeItem['workingExperienceInfo'].index(workingExperienceItem) - 1
                        preIndex = resumeItem['workingExperienceInfo'].index(workingExperienceItem) + 1
                        beginDate = workingExperienceItem.get('beginDate')
                        endDate = workingExperienceItem.get('endDate')
                        if resumeItem['workingExperienceInfo'].index(workingExperienceItem) == 0:
                            resume_analysis['leaveingCount'] += 1
                        if nextIndex not in range(len(resumeItem['workingExperienceInfo'])):
                            workingSpanList.append(format_trans_workingYearSpan(beginDate,endDate))
                        else:
                            workingSpanList.append(format_trans_workingYearSpan(beginDate,endDate))
                            nextCompanyList.append(resumeItem['workingExperienceInfo'][nextIndex].get('companyName'))
                        if preIndex not in range(len(resumeItem['workingExperienceInfo'])):
                            workingSpanList.append(format_trans_workingYearSpan(beginDate,endDate))
                        else:
                            workingSpanList.append(format_trans_workingYearSpan(beginDate,endDate))
                            preCompanyList.append(resumeItem['workingExperienceInfo'][preIndex].get('companyName'))


        resume_analysis['preCompany'] = Counter(list(set(preCompanyList)))
        resume_analysis['nextCompany'] = Counter(list(set(nextCompanyList)))
        resume_analysis['sexInfo'] = Counter(sexList)
        resume_analysis['location'] = Counter(locationList)
        resume_analysis['ageInfo'] = float(sum(ageList))/(float(len(ageList))+0.0001)
        if len(ageList) == 0.0:
            resume_analysis['ageInfo'] = None
        resume_analysis['degreeInfo'] = Counter(degreeList)
        resume_analysis['majorInfo'] = Counter(majorList)
        resume_analysis['schoolInfo'] = Counter(schoolList)
        resume_analysis['workingYearSpan'] = round(float(sum(workingSpanList))/(float(len(workingSpanList))+0.0001),1)
        if len(workingSpanList) == 0.0:
            resume_analysis['workingYearSpan'] = None
        resume_analysis['workingExperienceInfo'] = round(float(sum(workingExperienceList))/(float(len(workingExperienceList))+0.0001),1)
        if len(workingExperienceList) == 0.0:
            resume_analysis['workingExperienceInfo'] = None
        return resume_analysis
    except Exception, e:
        logger.info('FUN[companyResume_analysis] failed for:' + str(e))


def parse_leaveing_company_time(resumeItem, companyName):
    Findcompany = False
    leaveingTime = ''
    if resumeItem.get('workingExperienceInfo') :
        for workingExperienceItem in resumeItem['workingExperienceInfo']:
            if workingExperienceItem.get('companyName') == companyName:
                leaveingTime = workingExperienceItem.get('endDate',datetime.datetime.now().strftime('%Y-%m-%d'))
                Findcompany = True
                break
    return leaveingTime, Findcompany